// mobile bind
// ============

define(['zepto', 'utils', 'JST', 'sui'], function($, utils, JST){
  return {
    init: function(__CTX__, data) {
      this._CTX_ = __CTX__;
      this.data = data
      
      var groupDisplay = new Array(),
          groupValue = new Array();
      $.each(data.groups, function(k, group) {
        groupDisplay[k] = group.name;
        groupValue[k] = group.id;
      })
      
      this.groupDisplay = groupDisplay;
      this.groupValue   = groupValue;
      
      this.$bindButton = $('[href="#group-btn"]')
      this.$bindButton.length ? this.bindTagBindingAction() : void 0
    },

    /**
     * Bind action fired on clicking mobile binding button
     */
    bindTagBindingAction: function() {
      var that = this

      // On binding mobile
      this.$bindButton.on('click', function(e) {
        that.currentBtn = this;
        e.preventDefault()
        
        $(".courseware-searchbar").hide();
        $(".partition-line").hide();
        
        var $page = that.compileTagBindingPage()
        $.push.transitionIn($page, function() {
            
            $("#group-picker").picker({
                toolbarTemplate: '<header class="bar bar-nav">\
                                    <button class="button button-link pull-right close-picker">确定</button>\
                                    <h1 class="title">请选择动作组</h1>\
                                  </header>',
              cols: [{
                  textAlign: 'center',
                  values: that.groupValue,
                  displayValues: that.groupDisplay
                }],
              formatValue: function (picker, value, displayValue){
                  $(this.input).next().val(value)
                  return displayValue
              },
            });
            
            $page.on('click', '#submit', function(e) {
              e.preventDefault();
              var groupId = $page.find("input[name='groupId']").val();
              
              var submiting = that.submit(groupId);
            })
        })
      })

    },
    
    /**
     * Compile mobile binding page and return jQuery object
     */
    compileTagBindingPage: function() {
      var $page = $(JST.courseActionGroupTpl())
      return $page
    },
    
    submit: function(groupId) {
      var that = this
      var url = that._CTX_.root + '/rounds/'+that.data.roundId+'/course-coursewares/'+that.data.courseScheduleId+'/coursewares/action-group';
      $.showIndicator()
      $.post(url, {"groupId": groupId})
      .done(function(response) {
        $.hideIndicator()
        utils.processResult(response, function(result) {
          window.location.reload();
          /*window.location.href = that._CTX_.root + '/rounds/'+that.data.roundId+'/course-courseware/edit'*/
        }, function(result) {
          $.toast(result.message || '提交失败')
        })
      })
    }
  }

})

